package com.license.servlets;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.license.common.util.Constants;
import com.license.logic.pojo.User;

/**
 * Created with IntelliJ IDEA.
 * User: Ionuc
 * Date: 10/26/12
 * Time: 8:07 PM
 * To change this template use File | Settings | File Templates.
 */
public class AuthorizationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        String[] urlSplit = url.split("/");
        String path = urlSplit[urlSplit.length - 1];

        String redirect = null;
        User currentUser = (User) request.getSession().getAttribute("currentSessionUser");
        
        if (path.equals(Constants.START_PAGE)){
        	if (currentUser == null){
            	redirect = "../JSFfiles/" + Constants.NOT_AUTHORIZATION_PAGE;
            }
        }
        
        if (path.equals(Constants.DASHBOARD_PAGE)){
        	if (currentUser == null){
            	redirect = "../JSFfiles/" + Constants.NOT_AUTHORIZATION_PAGE;
            }
        }
        
        if (path.equals(Constants.EDIT_USER_PAGE)){
        	if (currentUser == null){
            	redirect = "../JSFfiles/" + Constants.NOT_AUTHORIZATION_PAGE;
            }
        }
        
        if (path.equals(Constants.USERS_PAGE)){
        	if (currentUser == null){
            	redirect = "../JSFfiles/" + Constants.NOT_AUTHORIZATION_PAGE;
            }
        }
        
        if (path.equals(Constants.INVALID_LOGIN_PAGE)){
        	if (currentUser != null){
            	redirect = "../JSFfiles/" + Constants.NOT_AUTHORIZATION_PAGE;
            }
        }
        if (redirect != null) {
            response.sendRedirect(redirect);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
